package com.nanuminc.market.today.type;

import java.util.ArrayList;

import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nanuminc.market.NMConstants;
import com.nanuminc.market.R;
import com.nanuminc.market.R.array;
import com.nanuminc.market.R.drawable;
import com.nanuminc.market.R.id;
import com.nanuminc.market.R.layout;
import com.nanuminc.market.R.string;
import com.nanuminc.market.common.TimeLineAdapter;
import com.nanuminc.market.common.TimeLineList;
import com.nanuminc.market.today.TodayFullView;
import com.nanuminc.market.today.TodaySearch;
import com.nanuminc.market.today.detail.TodayDetailView;
import com.nanuminc.market.utils.DomParserUtil;
import com.nanuminc.market.utils.ImageUtil;
import com.nanuminc.market.utils.XMLUtil;

public class TodayListC extends Activity implements OnClickListener {

	ArrayList<TimeLineList> arItem;
	int totalListNum = 0;
	Context context;
	TimeLineAdapter myAdapter;
	ListView mainList;
	int UpdateFlag = 0;
	int itemNum = 0;
	public LinearLayout mAddView;
	private static final int DIALOG_LOCAL_AREA = 1;
	private static final int DIALOG_CATEGORY = 2;
	private static final int DIALOG_SEARCH = 3;
	int localPosition = 0, categoryPosition = 0;

	TextView title_left, title_right, title_center;
	String searchStr;
	// AB급
	String mainListUrl_A;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.todaylist);

		context = getApplicationContext();
		// Timeline 리스트 호출
		createThreadAndDialog();
		mAddView = (LinearLayout) View.inflate(this, R.layout.addview, null);

		title_left = (TextView) findViewById(R.id.btn_location);
		title_center = (TextView) findViewById(R.id.btn_title);
		title_right = (TextView) findViewById(R.id.btn_search);
		title_left.setOnClickListener(this);
		title_center.setOnClickListener(this);
		title_right.setOnClickListener(this);

		
	}

	/*private ProgressDialog loagindDialog;*/ // Loading Dialog

	void createThreadAndDialog() {
		/* ProgressDialog */
		/*loagindDialog = ProgressDialog.show(this, "로딩 중", "잠시만 기다려 주세요....",
				true, false);*/

		Thread thread = new Thread(new Runnable() {
			public void run() {
				// HttpPostTimeLine();
				arItem = new ArrayList<TimeLineList>();
				ImageUtil imgutil = new ImageUtil();
				totalListNum = 15; // test;
				if (totalListNum > 10) {
					for (itemNum = 0; itemNum < 10; itemNum++) {
						arItem.add(new TimeLineList(NMConstants.LIST_C,
								"헤어빈", "염색+파마시 클리닉 무료",
								"거리 : 13m", null, null, null, false));
					}
				} else {
					for (itemNum = 0; itemNum < totalListNum; itemNum++) {
						arItem.add(new TimeLineList(NMConstants.LIST_C,
								"헤어빈", "염색+파마시 클리닉 무료",
								"거리 : 13m", null, null, null, false));
					}
				}

				handler.sendEmptyMessage(0);

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		});
		thread.start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			/*loagindDialog.dismiss();*/

			myAdapter = new TimeLineAdapter(context, arItem);
			mainList = (ListView) findViewById(R.id.mainlist);

			mAddView.setVisibility(View.INVISIBLE);
			mainList.addFooterView(mAddView);

			if (UpdateFlag == 1) {
				myAdapter.notifyDataSetChanged();
			}
			mainList.setAdapter(myAdapter);
			// if(tokpo == 0) tokpo++; // TestLine
			// mainList.setSelectionFromTop(tokpo, 0); // 0326 Append, Good

			ListClick();
			mainList.setOnScrollListener(new OnScrollListener() {

				@SuppressWarnings("unchecked")
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
						Log.v("nanum", "IN, totalItemCount = " + totalItemCount);

						if (totalListNum > itemNum) {
							mAddView.setVisibility(View.VISIBLE);
							new getMoreItems().execute(arItem);
						} else {
							mAddView.setVisibility(View.INVISIBLE);
						}

						Log.v("nanum", "IN END");
					}
				}

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub

				}

			});
		}
	};

	public void ListClick() {
		mainList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == totalListNum) {
					mainListUrl_A = "";

					// tokpo = position - 1;

					UpdateFlag = 1;
					createThreadAndDialog();

				} else {
					Intent intent = new Intent(TodayListC.this,
							TodayDetailView.class);
					startActivity(intent);
				}
			}
		});
	}

	public void HttpPostTimeLine() {

		String getxml;
		DomParserUtil parser = new DomParserUtil();

		getxml = XMLUtil.getXml(""); // API 호출
		Log.e("nanum", "getxml = " + getxml);

		NodeList node = parser.getNodeList(parser.getDomElement(getxml), "");

		totalListNum += node.getLength();

	}

	private class getMoreItems extends
			AsyncTask<ArrayList<TimeLineList>, Integer, Long> {

		@Override
		protected Long doInBackground(ArrayList<TimeLineList>... params) {
			// TODO Auto-generated method stub
			Long result = 0L;

			if (totalListNum >= itemNum + 10) {
				int tmpEnd = itemNum + 10;

				Log.v("nanum", "if > itemNum = " + itemNum);
				// imgutil.getPhoto(0, context,
				// thumbnailUrl_array.get(itemNum));
				// Bitmap bit = imgutil.mBit;
				Bitmap bit = BitmapFactory.decodeResource(getResources(),
						R.drawable.uie);
				for (; itemNum < tmpEnd; itemNum++) {
					arItem.add(new TimeLineList(NMConstants.LIST_C,
							"헤어빈", "염색+파마시 클리닉 무료",
							"거리 : 13m", null, null, null, false));
				}
			} else {
				Log.v("nanum", "else ");
				// imgutil.getPhoto(0, context,
				// thumbnailUrl_array.get(itemNum));
				// Bitmap bit = imgutil.mBit;
				Bitmap bit = BitmapFactory.decodeResource(getResources(),
						R.drawable.uie);
				for (; itemNum < totalListNum; itemNum++) {
					arItem.add(new TimeLineList(NMConstants.LIST_C,
							"헤어빈", "염색+파마시 클리닉 무료",
							"거리 : 13m", null, null, null, false));
				}
			}
			Log.v("nanum", "changed!!");

			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				;
			} // 1초 지연. 네트워크 작업 등을 시뮬레이션

			return null;
		}

		public void onPostExecute(Long result) {
			myAdapter.notifyDataSetChanged();

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOCAL_AREA:
			return new AlertDialog.Builder(TodayListC.this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.local)
					.setSingleChoiceItems(R.array.local, 0,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Log.e("nanum", "Choice whichButton = "
											+ whichButton);
									localPosition = whichButton;
								}
							})
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/*
									 * 확인 하면 다시 업데이트 시켜준다
									 */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked No so do some stuff */
								}
							}).create();
		case DIALOG_CATEGORY:
			return new AlertDialog.Builder(TodayListC.this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.local)
					.setSingleChoiceItems(R.array.category, 0,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Log.e("nanum", "Choice whichButton = "
											+ whichButton);
									categoryPosition = whichButton;
								}
							})
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/*
									 * 확인 하면 다시 업데이트 시켜준다
									 */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked No so do some stuff */
								}
							}).create();
		case DIALOG_SEARCH:
			// This example shows how to add a custom layout to an AlertDialog
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.dialogsearch,
					null);
			return new AlertDialog.Builder(TodayListC.this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.search)
					.setView(textEntryView)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked OK so do some stuff */
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_location:
			showDialog(DIALOG_LOCAL_AREA); // 지역설정
			break;
		case R.id.btn_title:
			showDialog(DIALOG_CATEGORY); // 카테고리
			break;
		case R.id.btn_search:
			Intent intent = new Intent(TodayListC.this, TodaySearch.class);
			startActivityForResult(intent, DIALOG_SEARCH);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode){
		case DIALOG_SEARCH:
			if(resultCode == RESULT_OK){
				searchStr = data.getStringExtra("SEARCH");
				Log.e("nanum","search = "+searchStr);
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}